package com.fivefu.core.camera.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class CmdUtils {

    private static Logger logger = LoggerFactory.getLogger(CmdUtils.class);

    /**
     * 判断当前系统是否linux系统
     * @return
     */
    public static boolean isLinux(){
        return System.getProperty("os.name").toLowerCase().contains("linux");
    }

    /**
     * 判断当前系统是否windows系统
     * @return
     */
    public static boolean isWindows(){
        return System.getProperty("os.name").toLowerCase().contains("windows");
    }

    /**
     * 执行cmd命令返回状态
     * @param cmd 执行命令
     * @return
     * @throws InterruptedException
     * @throws IOException
     */
    public static int execCommand(String cmd) throws InterruptedException, IOException {
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        if (isWindows()){
            process = runtime.exec("cmd.exe /c " + cmd);
        }else if (isLinux()){
            process = runtime.exec("/bin/sh -c " + cmd);
        }
        if (process == null){
            return 0;
        }
        int exitValue = process.waitFor();
        process.destroy();
        return exitValue;
    }

    /**
     * 执行cmd命令返回数据
     * @param cmd 执行命令
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public static Map<String, Object> execCommandAndGetOutput(String cmd) throws IOException, InterruptedException {
        Map<String,Object> backMap = new HashMap<>();

        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        if (isWindows()) {
            process = runtime.exec("cmd.exe /c " + cmd);
        }else if (isLinux()) {
            process = runtime.exec("/bin/sh -c " + cmd);
        }
        if (process == null){
            return backMap;
        }
        String result = getStreamStr(process.getInputStream());
        String errStr = getStreamStr(process.getErrorStream());

        int exitValue = process.waitFor();
        process.destroy();

        backMap.put("exitValue", exitValue);
        backMap.put("result", result);
        backMap.put("errStr", errStr);
        return backMap;
    }

    /**
     * 获取执行命令后返回的信息
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static String getStreamStr(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null){
            sb.append(line);
            sb.append("\n");
        }
        reader.close();
        return sb.toString();
    }

    /**
     * 执行cmd命令返回数据
     * @param cmd 执行命令
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public static String execute(String cmd) throws IOException, InterruptedException {
        BufferedReader br = null;
        File file = new File(System.getProperty("user.dir"));
        File tmpFile = new File(System.getProperty("user.dir") + "\\temp.tmp");//临时文件存放地址
        if (!file.exists()){
            file.exists();
        }
        if (!tmpFile.exists()){
            tmpFile.createNewFile();
        }

        ProcessBuilder pb = null;
        if (isWindows()){
            pb = new ProcessBuilder().command("cmd.exe", "/c", cmd).inheritIO();
        }else if (isLinux()){
            pb = new ProcessBuilder().command("/bin/sh", "-c", cmd).inheritIO();
        }
        if (pb == null){
            return null;
        }

        pb.redirectErrorStream(true);//把控制台的红字转成黑子
        pb.redirectOutput(tmpFile);//输出执行结果
        int exitValue = pb.start().waitFor();//等待语句执行完成

        InputStream in = new FileInputStream(tmpFile);
        br = new BufferedReader(new InputStreamReader(in, "GBK"));
        /*String line;
        while ((line = br.readLine()) != null){
            System.out.println(line);
        }*/

        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null){
            sb.append(line);
            sb.append("\n");
        }

        br.close();
        br = null;
        tmpFile.delete();//删除临时文件
        logger.info("执行完成");
        return sb.toString();
    }

}
